const router = require('koa-router')()
const { query } = require('../db')
const jwt = require('jsonwebtoken')
const OSS = require('ali-oss')

const Request = require('koa2-request')

const giteePage = {
  client_id: '5e25a35a9736c3c1577af47c7e37238e9bc634272ef0b7e76d062a7438de085c',
  redirect_uri: 'http://192.168.137.243:8080/login',
  client_secret: 'e09683da9d8e6d7042a66e9772d9f3cced4696f521d39c7f89be5dbe4e7d2d06'
}

const OSSPage = new OSS({
  bucket: "1908akoa",
  region: 'oss-cn-beijing',
  accessKeyId: "LTAI5tM8EcmsJrB5FAvb2Kne",
  accessKeySecret: "e1KnuO0cVrmV5MqReD85SZvTjP3eGD"
})

router.post('/api/login', async (ctx, next) => {
  // 前端传来的参数

  console.log(ctx.request, '===========================')
  const { username, password } = ctx.request.body;

  console.log(username, password)

  // 判断数据库中是否存在用户和密码
  const data = await query(`select * from userlist where username="${username}" and password="${password}"`);

  if (data.length) {
    ctx.body = {
      code: 1,
      token: jwt.sign(data[0].id, '1908A')
    }
  } else {
    ctx.status = 401;

    ctx.body = {
      code: 0,
      msg: '用户名或者密码错误'
    }
  }

})

router.get('/api/getUserInfo', async (ctx, next) => {
  const { authorization } = ctx.request.headers;

  try {
    const id = jwt.verify(authorization, '1908A')

    // 通过id 换取用户信息
    const data = await query(`select * from userlist where id=${id}`)

    ctx.body = {
      code: 1,
      data: data[0]
    }
  } catch (error) {
    ctx.status = 401
    ctx.body = {
      code: 0,
      msg: '登录失效 请重新登录'
    }
  }
})

router.post('/api/giteeLogin', async (ctx) => {
  // 获取前端传来的code
  const { code } = ctx.request.body;

  // 通过code 换取用户在第三方的token
  // require: post: 传参方式form，返回结果是字符串形式
  const data = await Request('https://gitee.com/oauth/token', {
    method: 'post',
    form: {
      grant_type: "authorization_code",
      code,
      client_id: giteePage.client_id,
      redirect_uri: giteePage.redirect_uri,
      client_secret: giteePage.client_secret
    },
  })

  // 用户在第三方的token
  const token = JSON.parse(data.body).access_token

  // 通过token 换取用户在第三方的详细信息
  const res = await Request.get(`https://gitee.com/api/v5/user?access_token=${token}`)

  // 用户在第三方应用的信息
  const userInfo = JSON.parse(res.body)

  // 通过用户的id 判断用户是否存在与我的数据库中
  const user = await query(`select * from userlist where id=${userInfo.id}`)

  console.log(userInfo)

  if (!user.length) {
    // 将当前的用户添加到数据库中
    await query(`insert into userlist (username, password, name, id, img) values ("${userInfo.name}", "123", "${userInfo.name}", ${userInfo.id}, "${userInfo.avatar_url}")`)
  }

  ctx.body = {
    code: 1,
    token: jwt.sign(userInfo.id, '1908A')
  }
})

router.post('/api/upload', async (ctx) => {
  // 获取前端传来的文件信息
  const { file } = ctx.request.files;

  // 同过时间戳生成文件名称
  const fileanme = new Date().getTime() + file.name;

  // 将文件添加到oss中
  const data = await OSSPage.put(fileanme, file.path)

  // 更新图片到当前的用户信息中
  const { cookie } = ctx.request.headers;

  const token = cookie.replace('token=', "")

  // 解密token
  const id = jwt.verify(token, '1908A')

  // 更新用户头像
  await query(`update userlist set img="${data.url}" where id=${id}`)

  ctx.body = {
    code: 1,
    msg: '上传成功'
  }
})

// 获取区域
router.get('/api/getAddress', async (ctx) => {
  // 获取到数据库的区域列表
  let sql = `select * from address`
  const data = await query(sql)

  ctx.body = {
    code: 1,
    data
  }
})

// 添加list
router.post('/api/addList', async (ctx) => {
  const { title, address, date, form, delivery, resource } = ctx.request.body;

  // 添加的顺序 和数据库中的顺序一致 依次添加， 添加的类型 需要和数据库中的类型一致 
  await query(`insert into list values("${title}", "${address}", "${date}", ${delivery}, ${resource}, "${form}", null)`)

  ctx.body = {
    code: 1,
    msg: '添加成功'
  }
})

// 获取List
router.post('/api/getList', async (ctx) => {
  const data = await query('select * from list')

  ctx.body = {
    code: 1,
    data
  }
})



module.exports = router
